package com.fengdi.book.easy.String;

public class LongestCommonPrefix {
    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) return "";
        if (strs.length == 1) return strs[0];

        StringBuilder sb = new StringBuilder();
        int minLength = this.findMinLength(strs);
        System.out.println(minLength);

        for(int i = 0; i < minLength; i++) {
            if(isSame(strs, i)) {
                sb.append(strs[0].charAt(i));
            }else {
                break;
            }
        }

        return sb.toString();
    }

    private Boolean isSame(String[] strs, int index) {
        if(strs == null || strs.length <= 1) return false;

        for(int i = 1; i < strs.length; i++){
            if(strs[i].charAt(index) != strs[i-1].charAt(index)){
                return false;
            }
        }

        return true;
    }

    private int findMinLength(String[] strs) {
        if(strs == null || strs.length <= 1) return 0;

        int minLength = strs[0].length();

        for (int i = 1; i < strs.length; i++) {
            minLength = Math.min(minLength, strs[i].length());
        }

        return minLength;
    }
}
